extends Control



const ShopDetailsColumn = preload("res://tool/page/shop/ShopDetailsColumn.tscn")

onready var select_popup = $ListSearchPopup
onready var item_select = $addModal/VBoxContainer/name/ItemSelect

var edit_data = null

var data = null

func _ready():	
	$addModal.visible = false
	


func set_data(data):
	self.data = data
	
	$HBoxContainer/Label.text = "商店 【%s】 商品管理" % data["name"]
	
	state_update()

func state_update():
	if self.data:
		var box = $table/ScrollContainer/VBoxContainer
		
		for child in box.get_children():
			child.queue_free()
			
		for data in DataSource.get_data_by_list(DataSource.shop_details, self.data["id"], "shopId"):
			var ui_item = ShopDetailsColumn.instance()
			ui_item.set_data(data)
			box.add_child(ui_item)
			
			ui_item.connect("delete", self, "_on_delete")
			ui_item.connect("edit", self, "_on_edit")
		

func _on_addBtn_button_up():
	edit_data = null
	$addModal.visible = true
	state_update_modal()
	


func _on_cancel_button_up():
	$addModal.visible = false


func _on_ok_button_up():
	# 读取数据
	var drama_data = {
		"itemId": item_select.get_value(),
		"shopId": data["id"]
	}
		
		
	if drama_data["itemId"] <= 0:
		MainTool.toast_info("道具不能为空")
		return
	
	for data in DataSource.get_data_by_list(DataSource.shop_details, self.data["id"], "shopId"):
		if data["itemId"] == drama_data["itemId"]:
			MainTool.toast_info("不可重复添加道具")
			return
		
	if edit_data:
		drama_data["id"] = edit_data["id"]
		DataSource.update_data(DataSource.shop_details, drama_data)
	else:
		DataSource.add_data(DataSource.shop_details, drama_data)	
	
	$addModal.visible = false
	state_update()


func state_update_modal():
	if edit_data:
		
		item_select.set_value(edit_data["id"])
		
		$addModal/modalTitle.text = "编辑商品：%s" % [edit_data["name"]]
		$addModal/btns/ok.text = "确认"
	else:
		$addModal/modalTitle.text = "添加商品"
		$addModal/btns/ok.text = "确认"


func _on_delete(data):
	var item_info = DataSource.get_item_by_id(data["itemId"])
	MainTool.confirm("你是否确认删除商品:%s" % item_info["name"], self, "_on_del_ok", null, data["id"])
	


func _on_del_ok(id):
	DataSource.delete_data_by_id(DataSource.shop_details, id)
	state_update()
	

func _on_edit(data):
	edit_data = data
	$addModal.visible = true
	state_update_modal()

# 点击返回
func _on_close_button_up():
	MainTool.getUILayer().pop_ui()

